package com.dashan.frontend.client;

import static com.dashan.Constants.COOKIE_NAME;
import static com.dashan.Constants.ONE_MONTH_MS;

import java.util.Date;

import com.google.gwt.user.client.Cookies;

public class DashanCookie {
    private String userName = ""; 
    private String sessionId = "";
    
    public DashanCookie(String userName, String sessionId) {
        this.userName = userName;
        this.sessionId = sessionId;
    }
    
    public DashanCookie(String value) {
        if (value != null) {
            String[] values = value.split(":");
            if (values.length == 2) {
                userName = values[0];
                sessionId = values[1];
            }
        }
    }
    
    /** {@code null} for cookie not exist. */
    public static DashanCookie load() {
        String cookie = Cookies.getCookie(COOKIE_NAME);
        if (cookie != null) {
            return new DashanCookie(cookie);
        } else {
            return null;
        }
//        return new DashanCookie("test@gmail.com:0");
        
    }
    
    public String getValue() {
        return userName + ":" + sessionId;
    }
    
    public void save() {
        Date now = new Date();
        Cookies.setCookie(COOKIE_NAME, getValue(), new Date(now.getTime() + ONE_MONTH_MS));
    }

    public String getUserName() {
        return userName;
    }

    public String getSessionId() {
        return sessionId;
    }
    
    public static void clear() {
        Cookies.removeCookie(COOKIE_NAME);
    }
}
